package com.newshub.business.controller;

import com.newshub.business.dto.SourceQueryDTO;
import com.newshub.business.entity.Source;
import com.newshub.business.service.SourceService;
import com.newshub.logging.annotation.BusinessLog;
import com.newshub.logging.annotation.LogLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 新闻源管理控制器
 */
@RestController
@RequestMapping("/api/source")
@CrossOrigin(origins = "*")
public class SourceController {
    
    @Autowired
    private SourceService sourceService;
    
    /**
     * 分页查询新闻源
     */
    @PostMapping("/list")
    @BusinessLog(level = LogLevel.INFO, description = "分页查询新闻源")
    public Map<String, Object> getSourceList(@RequestBody SourceQueryDTO queryDTO) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 参数验证
            if (queryDTO.getPageNum() == null || queryDTO.getPageNum() < 1) {
                queryDTO.setPageNum(1);
            }
            if (queryDTO.getPageSize() == null || queryDTO.getPageSize() < 1) {
                queryDTO.setPageSize(10);
            }
            
            // 查询数据
            List<Source> sources = sourceService.getSourcesByPage(queryDTO);
            long total = sourceService.countSourcesByPage(queryDTO);
            
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", sources);
            result.put("total", total);
            result.put("pageNum", queryDTO.getPageNum());
            result.put("pageSize", queryDTO.getPageSize());
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "查询失败：" + e.getMessage());
            result.put("data", null);
        }
        
        return result;
    }
    
    /**
     * 根据ID查询新闻源
     */
    @GetMapping("/{id}")
    public Map<String, Object> getSourceById(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Source source = sourceService.getSourceById(id);
            if (source != null) {
                result.put("code", 200);
                result.put("message", "查询成功");
                result.put("data", source);
            } else {
                result.put("code", 404);
                result.put("message", "新闻源不存在");
                result.put("data", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "查询失败：" + e.getMessage());
            result.put("data", null);
        }
        
        return result;
    }
    
    /**
     * 新增新闻源
     */
    @PostMapping("/add")
    @BusinessLog(level = LogLevel.INFO, description = "新增新闻源")
    public Map<String, Object> addSource(@RequestBody Source source) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 参数验证
            if (source.getName() == null || source.getName().trim().isEmpty()) {
                result.put("code", 400);
                result.put("message", "新闻源名称不能为空");
                return result;
            }
            
            if (source.getCode() == null || source.getCode().trim().isEmpty()) {
                result.put("code", 400);
                result.put("message", "新闻源代码不能为空");
                return result;
            }
            
            // 检查名称是否重复
            Source existingSource = sourceService.getSourceByName(source.getName().trim());
            if (existingSource != null) {
                result.put("code", 400);
                result.put("message", "新闻源名称已存在");
                return result;
            }
            
            // 检查代码是否重复
            existingSource = sourceService.getSourceByCode(source.getCode().trim());
            if (existingSource != null) {
                result.put("code", 400);
                result.put("message", "新闻源代码已存在");
                return result;
            }
            
            // 新增新闻源
            boolean success = sourceService.addSource(source);
            if (success) {
                result.put("code", 200);
                result.put("message", "新增成功");
                result.put("data", source);
            } else {
                result.put("code", 500);
                result.put("message", "新增失败");
                result.put("data", null);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "新增失败：" + e.getMessage());
            result.put("data", null);
        }
        
        return result;
    }
    
    /**
     * 更新新闻源
     */
    @PutMapping("/update")
    @BusinessLog(level = LogLevel.INFO, description = "更新新闻源")
    public Map<String, Object> updateSource(@RequestBody Source source) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 参数验证
            if (source.getId() == null) {
                result.put("code", 400);
                result.put("message", "新闻源ID不能为空");
                return result;
            }
            
            if (source.getName() == null || source.getName().trim().isEmpty()) {
                result.put("code", 400);
                result.put("message", "新闻源名称不能为空");
                return result;
            }
            
            if (source.getCode() == null || source.getCode().trim().isEmpty()) {
                result.put("code", 400);
                result.put("message", "新闻源代码不能为空");
                return result;
            }
            
            // 检查名称是否重复（排除自己）
            Source existingSource = sourceService.getSourceByName(source.getName().trim());
            if (existingSource != null && !existingSource.getId().equals(source.getId())) {
                result.put("code", 400);
                result.put("message", "新闻源名称已存在");
                return result;
            }
            
            // 检查代码是否重复（排除自己）
            existingSource = sourceService.getSourceByCode(source.getCode().trim());
            if (existingSource != null && !existingSource.getId().equals(source.getId())) {
                result.put("code", 400);
                result.put("message", "新闻源代码已存在");
                return result;
            }
            
            // 更新新闻源
            boolean success = sourceService.updateSource(source);
            if (success) {
                result.put("code", 200);
                result.put("message", "更新成功");
                result.put("data", source);
            } else {
                result.put("code", 500);
                result.put("message", "更新失败");
                result.put("data", null);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "更新失败：" + e.getMessage());
            result.put("data", null);
        }
        
        return result;
    }
    
    /**
     * 删除新闻源
     */
    @DeleteMapping("/{id}")
    @BusinessLog(level = LogLevel.WARN, description = "删除新闻源")
    public Map<String, Object> deleteSource(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean success = sourceService.deleteSource(id);
            if (success) {
                result.put("code", 200);
                result.put("message", "删除成功");
                result.put("data", null);
            } else {
                result.put("code", 500);
                result.put("message", "删除失败");
                result.put("data", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "删除失败：" + e.getMessage());
            result.put("data", null);
        }
        
        return result;
    }
    
    /**
     * 批量删除新闻源
     */
    @PostMapping("/delete/batch")
    public Map<String, Object> deleteBatchSources(@RequestBody List<Integer> ids) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (ids == null || ids.isEmpty()) {
                result.put("code", 400);
                result.put("message", "请选择要删除的新闻源");
                return result;
            }
            
            boolean success = sourceService.deleteBatchSources(ids);
            if (success) {
                result.put("code", 200);
                result.put("message", "批量删除成功");
                result.put("data", null);
            } else {
                result.put("code", 500);
                result.put("message", "批量删除失败");
                result.put("data", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "批量删除失败：" + e.getMessage());
            result.put("data", null);
        }
        
        return result;
    }
    
    /**
     * 更新新闻源状态
     */
    @PutMapping("/{id}/status")
    public Map<String, Object> updateSourceStatus(@PathVariable Integer id, @RequestParam Integer status) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (status == null || (status != 0 && status != 1)) {
                result.put("code", 400);
                result.put("message", "状态值无效");
                return result;
            }
            
            boolean success = sourceService.updateSourceStatus(id, status);
            if (success) {
                result.put("code", 200);
                result.put("message", "状态更新成功");
                result.put("data", null);
            } else {
                result.put("code", 500);
                result.put("message", "状态更新失败");
                result.put("data", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "状态更新失败：" + e.getMessage());
            result.put("data", null);
        }
        
        return result;
    }
    
    /**
     * 获取所有启用的新闻源
     */
    @GetMapping("/enabled")
    public Map<String, Object> getAllEnabledSources() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<Source> sources = sourceService.getAllEnabledSources();
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", sources);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "查询失败：" + e.getMessage());
            result.put("data", null);
        }
        
        return result;
    }
    
    /**
     * 根据区域ID查询新闻源
     */
    @GetMapping("/region/{regionId}")
    public Map<String, Object> getSourcesByRegionId(@PathVariable Integer regionId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<Source> sources = sourceService.getSourcesByRegionId(regionId);
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", sources);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "查询失败：" + e.getMessage());
            result.put("data", null);
        }
        
        return result;
    }
}
